package controller

import (
	"github.com/gin-gonic/gin"
	"math/rand"
	"net/http"
	"strconv"
	"user_bff/model/redis"
	"user_bff/pkg"
)

// 发送短信验证码
func SendSms(c *gin.Context) {
	mobile := c.PostForm("mobile")
	if mobile == "" {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": -1,
			"msg":  "手机号不能为空",
			"data": nil,
		})
		return
	}
	code := rand.Intn(100000)
	_, err := pkg.SendSms(mobile, strconv.Itoa(code))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": -1,
			"msg":  "短信验证码发送失败",
			"data": nil,
		})
		return
	}
	err = redis.SetSendSms(mobile, strconv.Itoa(code))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": -1,
			"msg":  "redis存储失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "短信验证码发送成功",
		"data": nil,
	})
	return
}
